<template style="overflow: auto; height: 90%; ">
  <el-dialog
    title="消息通知"
    :visible.sync="dialogVisible"
    width="55%"
    :height="'90%'"
  >
    <div class="agree-body"  >
      <div class="order-management">

        <el-input
          v-model="fromName"
          placeholder="寄件人姓名"
          clearable
          style="margin-bottom: 10px;width: 140px;"
        ></el-input>

        <el-input
          v-model="fromMobile"
          placeholder="寄件人电话"
          clearable
          style="margin-bottom: 10px;width: 150px;"
        ></el-input>
        <!-- 编号搜索框 -->
        <el-input
          v-model="companyBillCode"
          placeholder="订单编号"
          clearable
          style="margin-bottom: 10px;width: 170px;"
        ></el-input>
        <el-input
          v-model="courierCompanyWaybillNo"
          placeholder="运单号"
          clearable
          style="margin-bottom: 10px;width: 170px;"
        ></el-input>
        <el-button type="primary" @click="handleSearch">搜索</el-button>

        <el-row :gutter="20">
          <!-- 左侧树形结构 -->
          <el-col :span="8">
            <el-card>
              <el-tree
                :data="orderTreeData"
                :props="treeProps"
                node-key="id"
                highlight-current
                default-expand-all
                :current-node-key="currentNodeKey"
                @node-click="handleNodeClick"
              >
                <!-- 自定义节点内容 -->
                <template #default="{ node, data }">
              <span
                :class="{
                  'first-level-node': ['completed', 'canceled','24hour', 'logistics'].includes(data.id), // 第一级节点
                  'highlight-node': !['completed', 'canceled','24hour', 'logistics'].includes(data.id) && !clickedNodes.includes(data.id), // 子节点默认高亮
                  'clicked-node': clickedNodes.includes(data.id) // 已点击的节点
                }"
              >
                {{ node.label }}
              </span>
                </template>

              </el-tree>
            </el-card>
          </el-col>

          <!-- 右侧订单详情 -->
          <el-col :span="16">
            <el-card>
              <div v-if="selectedOrder">
                <h3>订单详情</h3>
                <p><strong>运单号:</strong> {{ selectedOrder.courierCompanyWaybillNo }}
                  <i
                    class="el-icon-document-copy copy"
                    @click="copy(selectedOrder.courierCompanyWaybillNo)"
                  ></i>
                </p>
<!--                <p><strong>所属店铺:</strong> {{ selectedOrder.goodsName }}</p>-->
<!--                <p><strong>订单编号:</strong> {{ selectedOrder.goodsName }}</p>-->
                <p><strong>物品名称:</strong> {{ selectedOrder.goodsName }}</p>
                <p><strong>创建时间:</strong> {{ selectedOrder.createTime }}</p>
                <p><strong>发货人信息:</strong> {{ selectedOrder.fromName }} {{ selectedOrder.fromMobile }}</p>
                <p><strong>发货地址:</strong> {{ selectedOrder.fromProv }}{{ selectedOrder.fromCity }}{{ selectedOrder.fromArea }}{{ selectedOrder.fromAddress }}</p>
                <p><strong>收货人信息:</strong> {{ selectedOrder.toName }} {{ selectedOrder.toMobile }}</p>
                <p><strong>收货地址:</strong> {{ selectedOrder.toProv }}{{ selectedOrder.toCity }}{{ selectedOrder.toArea }}{{ selectedOrder.toAddress }}</p>
                <p v-if="selectedOrder.timeoutDay"><strong>未取件天数:</strong> {{ selectedOrder.timeoutDay }} 天</p>
                <p v-if="selectedOrder.reason"><strong>退货原因:</strong> {{ selectedOrder.reason }}</p>
                <el-button style="margin-left: -2px" type="text"  @click="toQueryCourierTrack(selectedOrder.id)">查看物流信息</el-button>
                <div v-if="logisticsInfo != null && logisticsInfo.length > 0">
                  <h3>物流信息</h3>
                  <!-- 显示物流信息 -->
                  <el-steps direction="vertical" :active="1">
                    <div v-for="(item, index) in logisticsInfo" :key="index">
                      <el-step
                        :title="item.opDesc"
                        :description="item.opTime"
                      ></el-step>
                    </div>
                  </el-steps>
                </div>
              </div>
              <div v-else>
                <p>请选择一个订单查看详情</p>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </div>
  </el-dialog>
</template>
<script>
import { queryCourierTrack,courierOrderList,saveMagRecord } from "@/api/cexpressorder/ziorder/orderList";
export default {
  data() {
    return {
      dialogVisible: true,
      fromName: "",
      fromMobile: "",
      companyBillCode: "",
      courierCompanyWaybillNo: "",
      logisticsInfo: [],
      clickedNodes: [], // 已点击的节点 ID 列表
      // 树形结构数据
      orderTreeData: [

        {
          id: 'canceled',
          label: '快递员取消订单',
          children: [

          ] // 动态加载取消订单
        },
        {
          id: '24hour',
          label: '24小时未取件',
          children: [

          ] // 动态加载取消订单
        },{
          id: 'completed',
          label: '已完成取件订单',
          children: [

          ] // 动态加载已完成订单
        },
      ],
      // 树形结构配置
      treeProps: {
        label: 'label',
        children: 'children'
      },
      currentNodeKey: '', // 当前高亮节点的 key
      selectedOrder: null // 当前选中的订单详情
    };
  },
  created() {
    this.fetchCompletedOrders();
    this.fetchCanceledOrders();
    this.fetch24hourOrders();
  },
  methods: {
    hideDialog() {
      this.dialogVisible = false;
    },
    showDialog() {
      this.dialogVisible = true;
    },
    // 获取已完成取件订单列表
     fetchCompletedOrders() {
      try {
        const completedNode = this.orderTreeData.find(node => node.id === 'completed');
        courierOrderList({ page: 0,size:1000 ,pageNo: 1,pageSize:10000,pagetype:4,orderState:2
          ,fromName:this.fromName,fromMobile:this.fromMobile,companyBillCode:this.companyBillCode,courierCompanyWaybillNo:this.courierCompanyWaybillNo,isMsgQuery:"Y"
        }).then((res) => {
          let data = [];
          res.data.items.forEach(item => {
            data.push({id: item.id, label: item.id})
          });
          completedNode.children = res.data.items.map(order => ({
            id: order.id,
            label: order.courierCompanyWaybillNo,
            ...order
          }));
        });


      } catch (error) {
        console.error('获取已完成订单失败:', error);
      }
    },
    // 获取快递员取消订单列表
     fetchCanceledOrders() {
      try {
        const canceledNode = this.orderTreeData.find(node => node.id === 'canceled');
        courierOrderList({ page: 0,size:50 ,pageNo: 1,pageSize:50,pagetype:4,orderState:4
          ,fromName:this.fromName,fromMobile:this.fromMobile,companyBillCode:this.companyBillCode,courierCompanyWaybillNo:this.courierCompanyWaybillNo,isMsgQuery:"Y"
        }).then((res) => {
          let data = [];
          res.data.items.forEach(item => {
            data.push({id: item.id, label: item.id})
          });
          canceledNode.children = res.data.items.map(order => ({
            id: order.id,
            label: order.courierCompanyWaybillNo,
            ...order
          }));
        });
      } catch (error) {
        console.error('获取取消订单失败:', error);
      }
    },
    fetch24hourOrders() {
      try {
        const canceledNode = this.orderTreeData.find(node => node.id === '24hour');
        courierOrderList({ page: 0,size:100 ,pageNo: 1,pageSize:100,pagetype:4,orderState:3
          ,fromName:this.fromName,fromMobile:this.fromMobile,companyBillCode:this.companyBillCode,courierCompanyWaybillNo:this.courierCompanyWaybillNo,isMsgQuery:"Y"
        }).then((res) => {
          let data = [];
          res.data.items.forEach(item => {
            data.push({id: item.id, label: item.id})
          });
          canceledNode.children = res.data.items.map(order => ({
            id: order.id,
            label: order.courierCompanyWaybillNo,
            ...order
          }));
        });
      } catch (error) {
        console.error('获取取消订单失败:', error);
      }
    },
    // 处理树节点点击事件
    handleNodeClick(data) {
      if (data.id !== 'completed' && data.id !== 'canceled' && data.id !== '24hour') {
        this.selectedOrder = data; // 设置选中的订单
        this.logisticsInfo = []; // 清空物流信息
        this.saveClickedNode(data.id); // 调用后端接口保存点击记录

      }
    },
    toQueryCourierTrack(id) {
      queryCourierTrack(id).then((res) => {
        let data = [];
        let arr = Object.keys(res.data);
        arr.forEach(item => {
          data.push({opTime: item, opDesc: res.data[item]})
        });
        this.logisticsInfo = data;
      });
    },
    // 调用后端接口保存点击记录
    saveClickedNode(nodeId) {
      try {
        saveMagRecord({orderId:nodeId}).then((res) => {

        });
        this.clickedNodes.push(nodeId); // 添加到已点击节点列表
      } catch (error) {
        console.error('保存点击记录失败:', error);
      }
    },
    // 过滤节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.includes(value) || data.id.includes(value);
    },
    // 处理搜索
    handleSearch() {
      // this.$refs.tree.filter(this.searchQuery);
      this.logisticsInfo=[];
      this.selectedOrder =null;
      this.fetchCompletedOrders();
      this.fetchCanceledOrders();
      this.fetch24hourOrders();
    },
    copy(value) {
      if (navigator.clipboard === 1) {
        navigator.clipboard.writeText(value).then((res) => {
          this.$message({
            message: "复制成功",
            type: "success",
          });
        });
      } else {
        // 创建隐藏的 textarea
        const textArea = document.createElement("textarea");
        textArea.value = value;
        document.body.appendChild(textArea); // 添加到 DOM 中以便可以操作

        // 选中文本
        textArea.select();
        // 执行复制命令
        try {
          const isCopied = document.execCommand("copy");
          if (isCopied) {
            this.$message({
              message: "复制成功",
              type: "success",
            });
          }
        } catch (err) {
          console.error("无法复制文本: ", err);
        }

        // 复制完成后移除 textarea
        document.body.removeChild(textArea);
      }
    },


  }
};

</script>
<style>
.order-management {
  padding: 20px;
}
.el-select {
  width: 100%;
  margin-bottom: 20px;
}

.scroll-dialog {
  max-height: 90%; /* 设置最大高度 */
  overflow: auto; /* 或者使用 overflow: scroll; */
}

.clicked-node {
  color: #999; /* 已点击节点显示为灰色 */
}
.highlight-node {
  color: #409eff; /* 高亮节点显示为蓝色 */
}

.copy {
  color: #13ce66;
}
</style>
